package com.mall.order.biz.mq;

import com.mall.order.constants.OrderConstants;
import com.mall.order.dal.entitys.Order;
import com.mall.order.dal.entitys.OrderItem;
import com.mall.order.dal.entitys.Stock;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.order.dal.persistence.StockMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @Classname DelayOrderCancelConsumer
 * @Description NULL
 * @Date 2021/5/26 14:05
 * @Created by virus
 */
@Slf4j
@Component
public class DelayOrderCancelConsumer {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private StockMapper stockMapper;

    DefaultMQPushConsumer defaultMQPushConsumer;

    @PostConstruct
    @Transactional
    public void init() {
        defaultMQPushConsumer = new DefaultMQPushConsumer(DelayOrderCancelProducer.ORDER_DELAY_TOPIC + "_consumer");
        defaultMQPushConsumer.setNamesrvAddr("127.0.0.1:9876");
        try {
            defaultMQPushConsumer.subscribe(DelayOrderCancelProducer.ORDER_DELAY_TOPIC, "*");
            defaultMQPushConsumer.registerMessageListener(new MessageListenerConcurrently() {
                @Override
                public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                    try {
                        Message message = list.get(0);
                        String orderId = new String(message.getBody(), 0, message.getBody().length, StandardCharsets.UTF_8);
                        Order order = orderMapper.selectByPrimaryKey1(orderId);
                        Integer status = order.getStatus();
                        if (!status.equals(OrderConstants.ORDER_STATUS_TRANSACTION_CLOSE)
                                || !status.equals(OrderConstants.ORDER_STATUS_TRANSACTION_FAILED)
                                || !status.equals(OrderConstants.ORDER_STATUS_TRANSACTION_SUCCESS)) {
                            order.setStatus(OrderConstants.ORDER_STATUS_TRANSACTION_CANCEL);
                            orderMapper.updateByPrimaryKey(order);
                        }
                        if (!status.equals(OrderConstants.ORDER_STATUS_TRANSACTION_SUCCESS)) {
                            List<OrderItem> orderItems = selectItemListByOrderId(orderId);
                            updateStock(orderItems);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                    }
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                }
            });
            defaultMQPushConsumer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }

    private List<OrderItem> selectItemListByOrderId(String orderId) {
        Example example = new Example(OrderItem.class);
        example.createCriteria().andEqualTo("orderId", orderId);
        return orderItemMapper.selectByExample(example);
    }

    private void updateStock(List<OrderItem> orderItems) {
        ArrayList<Long> itemIds = new ArrayList<>();
        for (OrderItem orderItem : orderItems) {
            itemIds.add(orderItem.getItemId());
        }
        List<Stock> stocksToUpdate = stockMapper.findStocksForUpdate(itemIds);
        for (Stock stock : stocksToUpdate) {
            stock.setStockCount(Long.valueOf(stock.getLockCount()));
            stock.setLockCount(-stock.getLockCount());
            stockMapper.updateStock(stock);
        }
    }

}
